import 'package:flutter/material.dart';
import 'package:projectfluttershengyihuatong/tab2/problemsolvHeader.dart';
import 'package:projectfluttershengyihuatong/tab2/problemsolvoptincell.dart';
import '../category/CatetoryModel.dart';
import '../tool/public_color.dart';
import '../tool/tool.dart';
import 'questionmodel.dart';
import 'questionlesson.dart';

class QuestionTab extends StatefulWidget {
  const QuestionTab({
    super.key,
    required this.dataArr,
    required this.catetoryModel,
    required this.chapterAndLesson,
    required this.model,
    required this.pageController,
  });

  final List<Question> dataArr;
  final CatetoryModel catetoryModel;
  final ChapterAndLesson chapterAndLesson;
  final Question model;
  final PageController pageController;

  @override
  State<QuestionTab> createState() => _QuestionTabState();
}

class _QuestionTabState extends State<QuestionTab> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 15, right: 15, bottom: 10),
      child: _isAddDragBtn ? ResizableColumn(
        topWidget: buildListView(),
        bottomWidget: buildListView(),
        initalTopHeight: 200,
      ): buildListView(),
    );
  }

  ListView buildListView() {
    return ListView(
      children: [
        ProblemSolvHeader(
            model: widget.model,
            dataArr: widget.dataArr,
            keStr: widget.catetoryModel.title ?? "",
            chapterStr: widget.chapterAndLesson.title ?? ""),
        builderHeader(model: widget.model),
        //titlte Image
        BuildTitleImage(model: widget.model),
        //
        if (widget.model.option != null && widget.model.option!.isNotEmpty)
          for (int i = 0; i < widget.model.option!.length; i++)
            QuestionOptionCell(
              model: widget.model,
              i: i,
              callback: (isSelected) {
                setState(() {});
                if (widget.model.questionType != 2) {
                  widget.pageController.animateToPage(widget.model.index,
                      duration: Duration(milliseconds: 500),
                      curve: Curves.easeInOutSine);
                }
              },
            ),
        BuildSureButton(
          model: widget.model,
          pageController: widget.pageController,
        ),
        //   是否查看答案
        BuildAnswer(model: widget.model),
        BuildAnalysis(model: widget.model)
      ],
    );
  }

  bool get _isAddDragBtn =>
      widget.model.questionCategory == 1 || widget.model.questionCategory == 2;

  Widget buildBack() {
    if (_isAddDragBtn) {
    } else {
      return buildListView();
    }

    return Container();
  }
}

class ResizableColumn extends StatefulWidget {
  const ResizableColumn(
      {super.key,
      required this.topWidget,
      required this.bottomWidget,
      this.minHeight = 150,
      this.initalTopHeight = 200})
      : assert(
            initalTopHeight > minHeight, "initalTop Height is more minHeight");

  final Widget topWidget;
  final Widget bottomWidget;
  final double minHeight;
  final double initalTopHeight;

  @override
  State<ResizableColumn> createState() => _ResizableColumnState();
}

class _ResizableColumnState extends State<ResizableColumn> {
  double _offset = 0.0;
  final dividerHeight = 40;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constaints) {
        final halfheight = constaints.maxHeight - widget.initalTopHeight;
        if (widget.initalTopHeight + _offset < widget.minHeight) {
          _offset = widget.minHeight - widget.initalTopHeight;
        } else if (halfheight - _offset < widget.minHeight) {
          _offset = halfheight - widget.minHeight;
        }

        return Column(
          children: [
            Container(
              height: widget.initalTopHeight + _offset - (dividerHeight * 0.5),
              child: widget.topWidget,
            ),
            DraggableDivider(
              dragUpdate: (y) {
                setState(() {
                  _offset += y;
                });
              },
            ),
            Container(
                height: halfheight - _offset - (dividerHeight * 0.5),
                child: widget.bottomWidget),
          ],
        );
      },
    );
  }
}

class DraggableDivider extends StatelessWidget {
  const DraggableDivider({super.key, required this.dragUpdate});

  final ValueChanged<double> dragUpdate;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onVerticalDragUpdate: (details) {
        this.dragUpdate(details.delta.dy);
      },
      child: Container(
        child: Center(
          child: Image.asset(
            assetImage("xiala"),
            height: 40,
            fit: BoxFit.fitHeight,
          ),
        ),
      ),
    );
  }
}

class builderHeader extends StatelessWidget {
  const builderHeader({
    super.key,
    required this.model,
  });

  final Question model;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10, bottom: 10),
      child: RichText(
        text: TextSpan(children: [
          TextSpan(
              text: model.typeStr,
              style: TextStyle(fontSize: 14, color: primaryColor)),
          TextSpan(
              text: model.title,
              style: TextStyle(
                fontSize: 16,
                color: color33,
              ))
        ]),
      ),
    );
  }
}

class BuildTitleImage extends StatelessWidget {
  const BuildTitleImage({
    super.key,
    required this.model,
  });

  final Question model;

  @override
  Widget build(BuildContext context) {
    final titleImage = model.titleImg ?? "";
    return titleImage.isNotEmpty
        ? Container(
            child: Image.network(
              model.titleImg!,
              fit: BoxFit.fitWidth,
            ),
          )
        : Container();
  }
}

class BuildAnalysis extends StatelessWidget {
  const BuildAnalysis({
    super.key,
    required this.model,
  });

  final Question model;

  @override
  Widget build(BuildContext context) {
    bool isShow = model.questionStatus == QuestionStatus.check;
    return isShow
        ? Container(
            child: Column(
              children: [
                Container(
                  margin: const EdgeInsets.only(top: 10, bottom: 10),
                  child: Row(
                    children: [
                      Expanded(
                          child: Container(
                        height: 1,
                        color: color99,
                      )),
                      const SizedBox(
                        width: 15,
                      ),
                      Text(
                        "试题解析",
                        style: TextStyle(
                            color: color66,
                            fontSize: 16,
                            fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(
                        width: 15,
                      ),
                      Expanded(
                        child: Container(
                          height: 1,
                          color: color99,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                Text(model.problemAnalysis ?? ""),
              ],
            ),
          )
        : Container();
  }
}

class BuildAnswer extends StatelessWidget {
  const BuildAnswer({
    super.key,
    required this.model,
  });

  final Question model;

  @override
  Widget build(BuildContext context) {
    bool isShow = model.questionStatus == QuestionStatus.check;

    return isShow
        ? Container(
            margin: const EdgeInsets.only(top: 20),
            child: Stack(
              children: [
                Container(
                  margin: const EdgeInsets.only(top: 24),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          offset: Offset.zero,
                          color: colorf1,
                          blurRadius: 5,
                          spreadRadius: 0,
                        ),
                      ]),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: Container(
                          child: Column(
                            children: [
                              Text(
                                "正确答案",
                                style: TextStyle(color: color66, fontSize: 14),
                              ),
                              SizedBox(
                                height: 4,
                              ),
                              Text(
                                model.answer ?? "",
                                style: TextStyle(
                                    color: primaryColor, fontSize: 15),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        width: 2,
                        height: 50,
                        color: colorf1,
                        margin: EdgeInsets.only(top: 15, bottom: 15),
                      ),
                      Expanded(
                        child: Container(
                            child: Column(
                          children: [
                            Text(
                              "我的答案",
                              style: TextStyle(color: color66, fontSize: 14),
                            ),
                            SizedBox(
                              height: 4,
                            ),
                            Text(
                              model.answer ?? "",
                              style:
                                  TextStyle(color: primaryColor, fontSize: 15),
                            ),
                          ],
                        )),
                      ),
                    ],
                  ),
                ),
                Positioned(
                    left: 2,
                    top: 0,
                    child: Container(
                      child: Image.asset(
                        assetImage("qb_error"),
                        width: 85,
                        height: 24,
                        fit: BoxFit.fitWidth,
                      ),
                    ))
              ],
            ),
          )
        : Container();
  }
}

class BuildSureButton extends StatefulWidget {
  const BuildSureButton({
    super.key,
    required this.model,
    required this.pageController,
  });

  final Question model;
  final PageController pageController;

  @override
  State<BuildSureButton> createState() => _BuildSureButtonState();
}

class _BuildSureButtonState extends State<BuildSureButton> {
  @override
  Widget build(BuildContext context) {
    bool isShow = true;
    MaterialStateProperty<Color> backgroundColor =
        MaterialStatePropertyAll(colorf9);
    Color textColor = color66;

    switch (widget.model.questionStatus) {
      case QuestionStatus.unAnswer:
        backgroundColor = MaterialStatePropertyAll(colorf1);
        break;
      case QuestionStatus.answerAndUnSure:
        backgroundColor = MaterialStatePropertyAll(primaryColor);
        textColor = Colors.white;

        break;
      case QuestionStatus.sureAnswer:
        isShow = false;
        textColor = Colors.white;
        backgroundColor = MaterialStatePropertyAll(primaryColor);
        break;
      case QuestionStatus.check:
        isShow = false;
        break;
      default:
        break;
    }
    if (widget.model.questionType == 2) {
      if (widget.model.questionStatus == QuestionStatus.sureAnswer) {
        isShow = false;
      } else {
        isShow = true;
      }
    } else {
      isShow = false;
    }

    return isShow
        ? Container(
            margin: const EdgeInsets.only(top: 10),
            child: Center(
              child: Container(
                child: LayoutBuilder(
                  builder: (context, constraint) {
                    print(constraint);
                    return ElevatedButton(
                      style: ButtonStyle(
                        shape: const MaterialStatePropertyAll(StadiumBorder()),
                        side: MaterialStatePropertyAll(
                            BorderSide(color: color66)),
                        elevation: const MaterialStatePropertyAll(0),
                        backgroundColor: backgroundColor,
                        fixedSize:
                            const MaterialStatePropertyAll(Size.fromWidth(200)),
                      ),
                      onPressed: () {
                        final result = widget.model.option
                                ?.where((element) => element.isSelected)
                                .toList() ??
                            [];
                        widget.model.myAnswer =
                            result.map((e) => e.icon).toList().join();
                        if (result.isNotEmpty) {
                          widget.model.questionStatus =
                              QuestionStatus.sureAnswer;
                          widget.pageController.animateToPage(
                              widget.model.index,
                              duration: const Duration(milliseconds: 500),
                              curve: Curves.easeInOutSine);
                          setState(() {});
                        }
                      },
                      child: Text(
                        "确定回答",
                        style: TextStyle(
                          color: textColor,
                          fontSize: 14,
                          wordSpacing: 4,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
          )
        : Container();
  }
}
